package com.summer.reference;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;

public class ReferenceTest1 {

	public static void main(String[] args) {
		ReferenceQueue < A >  rq  =   new  ReferenceQueue < A > ();
		A a = new A();
		B b = new B(new WeakReference<A>(a,rq).get());
		C c = new C(new WeakReference<A>(a,rq).get());
		
		int i=0;
		while(true){
			if(i>10)
				a=null;
			if(i>13)
				b=null;
			if(b!=null && b.getA() != null){
				System.out.println("b对象还存在"+i+" loops - "+b.getA());
			}else{
				System.out.println("b对象不存在了.");
			}
			if(c.getA() != null){
				i++;
				System.out.println("c对象还存在"+i+" loops - "+c.getA());
			}else{
				System.out.println("c对象不存在了.");
				break;
			}
			
			System.gc();
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	public static class A{
		public String name ="A";
	}
	
	public static class B{
		private A a;
		public B(A a){
			this.a=a;
		}
		
		public A getA(){
			return a;
		}
	}
	
	public static class C{
		private WeakReference<A> a;
		public C(A a){
			this.a=new WeakReference<A>(a);
		}
		
		public A getA(){
			return a.get();
		}
	}
	
	public static class D extends A{
		
		public D(){
		}
	}
}
